import { getToken } from "/@/utils/token";
import { ElMessage } from "element-plus";
import NProgress from "nprogress";
import "nprogress/nprogress.css"; // progress bar style
import router from "/@/router";
import { useActiveRouter } from "/@/store/activeRouter";

const whiteList: string[] = ["/login"];

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const activeRouter = useActiveRouter();

  const hasToken = getToken();
  if (hasToken) {
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      const hasRoles: boolean =
        activeRouter.list && activeRouter.list.length > 0;
      if (hasRoles) {
        next();
      } else {
        try {
          const list = (await activeRouter.getRouteList()) as any[];
          list.forEach((routes) => {
            router.addRoute(routes);
          });
          next({ ...to, replace: true });
        } catch (error) {
          ElMessage.error(error as string);
          console.log(from);
        }
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next({ path: "/login" });
    }
  }
});
router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
